﻿// Fill out your copyright notice in the Description page of Project Settings.


#include "BasicAttributeSet.h"
#include "GameplayEffectExtension.h"
#include "BaseCharacter.h"
#include "PlayerCharacter.h"
#include "EnemyCharacter.h"

void UBasicAttributeSet::PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue)
{
	//Super::PreAttributeChange(Attribute, NewValue);
	if (Attribute == GetMaxHealthAttribute())
	{
		AdjustAttributeForMaxChange(Health, MaxHealth, NewValue, GetHealthAttribute());
	}
	if (Attribute == GetMaxSteminaAttribute())
	{
		AdjustAttributeForMaxChange(Stemina, MaxStemina, NewValue, GetSteminaAttribute());
	}
	if (Attribute == GetEnemyMaxHealthAttribute())
	{
		AdjustAttributeForMaxChange(EnemyHealth, EnemyMaxHealth, NewValue, GetEnemyHealthAttribute());
	}
}

void UBasicAttributeSet::PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data)
{
	if (Data.EvaluatedData.Attribute == GetHealthAttribute())
	{
		SetMaxHealth(100);
		SetHealth(FMath::Clamp(GetHealth(), 0.0f, GetMaxHealth()));
		AActor* TargetActor = Data.Target.AbilityActorInfo->AvatarActor.Get();
		Player = Cast<APlayerCharacter>(TargetActor);
		if (GetHealth() <= 0)
		{
			//Player->Died();
		}
	}
	if (Data.EvaluatedData.Attribute == GetSteminaAttribute())
	{
		SetStemina(FMath::Clamp(GetStemina(), 0.0f, GetMaxStemina()));
	}
	if (Data.EvaluatedData.Attribute == GetEnemyHealthAttribute())
	{
		SetEnemyMaxHealth(150);
		SetEnemyHealth(FMath::Clamp(GetEnemyHealth(), 0.0f, GetEnemyMaxHealth()));
		AActor* TargetActor = Data.Target.AbilityActorInfo->OwnerActor.Get();
		AEnemyCharacter* Enemy = Cast<AEnemyCharacter>(TargetActor);
		if (GetEnemyHealth() <= 0)
		{
			Enemy->Dead();
		}
	}

	else if (Data.EvaluatedData.Attribute == GetDamageAttribute())
	{
		float CurrentDamage = GetDamage();
		if (CurrentDamage > 0)
		{
			SetDamage(0);
			SetHealth(FMath::Clamp(GetHealth() - CurrentDamage, 0.0f, GetMaxHealth()));
			AActor* TargetActor = Data.Target.AbilityActorInfo->AvatarActor.Get();
			ABaseCharacter* TargetCharacter = Cast<ABaseCharacter>(TargetActor);
			TargetCharacter->OnDamaged(CurrentDamage);
		}
	}
}

void UBasicAttributeSet::AdjustAttributeForMaxChange(FGameplayAttributeData& AffectedAttribute,
	const FGameplayAttributeData& MaxAttribute, float NewMaxValue,
	const FGameplayAttribute& AffectedAttributeProperty) 
{
	UAbilitySystemComponent* AbilityComp = GetOwningAbilitySystemComponent();
	const float CurrentMaxValue = MaxAttribute.GetCurrentValue();
	if (!FMath::IsNearlyEqual(CurrentMaxValue,NewMaxValue) && AbilityComp)
	{
		const float CurrentValue = AffectedAttribute.GetCurrentValue();
		float NewDelta = (CurrentMaxValue > 0.f) ? (CurrentValue * NewMaxValue / CurrentMaxValue)
			- CurrentValue : NewMaxValue;
		AbilityComp->ApplyModToAttributeUnsafe(AffectedAttributeProperty,
			EGameplayModOp::Additive, NewDelta);
	}
}

